<template>
	<view class="video-list-page">
		<!-- 视频容器，支持滑动 -->
		<view class="video-swiper" :style="{ transform: `translateY(${-currentIndex * 100}vh)` }">
			<view class="video-item" v-for="(video, index) in videoList" :key="getVideoKey(video, index)"
				:style="{ height: '100vh' }">
				<!-- 使用原生video组件 -->
				<video v-if="index === currentIndex && isValidVideo(video)" :id="`video-${getVideoKey(video, index)}`"
					:src="getVideoUrl(video)" :autoplay="true" :controls="false" class="video-player"
					object-fit="contain" @loadedmetadata="onVideoLoaded" @error="onVideoError" @play="onVideoPlay"
					@pause="onVideoPause"></video>

				<!-- 视频信息层 -->
				<view class="video-info">
					<text class="video-title">{{ video.content || `视频 ${index + 1}` }}</text>
				</view>

				<!-- 加载状态 -->
				<view v-if="index === currentIndex && loading" class="loading-indicator">
					<text>加载中...</text>
				</view>

				<!-- 视频无效提示 -->
				<view v-if="index === currentIndex && !isValidVideo(video)" class="video-invalid">
					<text class="invalid-text">视频不可用</text>
				</view>
			</view>
		</view>

		<!-- 蒙层 - 永远显示在视频上方 -->
		<view class="overlay-layer">
			<!-- 返回按钮 -->
			<view class="close-button" @tap="goBack">
				<text class="back-icon">←</text>
			</view>

			<!-- 指示器 -->
			<view class="video-indicator" v-if="videoList.length > 1">
				<view v-for="(video, index) in videoList" :key="getVideoKey(video, index)" class="indicator-dot"
					:class="{ active: index === currentIndex }"></view>
			</view>

			<!-- 空状态 -->
			<view v-if="videoList.length === 0 && !loading" class="empty-state">
				<text>暂无视频</text>
				<button class="refresh-btn" @tap="refreshVideos">重新加载</button>
			</view>
		</view>

		<!-- 调试信息 - 放在最上层 -->
		<view class="debug-info" v-if="showDebug">
			<text>当前索引: {{ currentIndex }}</text>
			<text>视频数量: {{ videoList.length }}</text>
			<text>滑动状态: {{ isSwiping ? '滑动中' : '静止' }}</text>
			<text>滑动锁定: {{ swipeLock ? '是' : '否' }}</text>
			<text>触摸坐标: {{ startY }} -> {{ moveY }}</text>
			<text>滑动距离: {{ touchDistance }}</text>
		</view>

		<!-- 专门的触摸层 - 修复版本 -->
		<view class="touch-layer" 
			@touchstart="handleTouchStart" 
			@touchmove="handleTouchMove"
			@touchend="handleTouchEnd"
			@touchcancel="handleTouchEnd"></view>
	</view>
</template>

<script>
	import {
		getVideos
	} from '@/request/api.js';
	export default {
		name: 'VideoListPage',
		data() {
			return {
				startY: 0,
				moveY: 0,
				touchStartTime: 0,
				swipeThreshold: 50, // 滑动阈值
				swipeTimeThreshold: 500, // 时间阈值
				currentIndex: 0,
				videoList: [], // 视频列表
				pageNum: 1,
				pageSize: 10,
				loading: false,
				hasMore: true,
				lastLoadIndex: 0,
				loadThreshold: 3,
				swipeLock: false, // 滑动锁防止快速滑动
				swipeLockTimeout: null,
				videoContexts: {}, // 存储视频上下文
				isSwiping: false, // 是否正在滑动
				initialVideo: null, // 从路由参数获取的初始视频
				showDebug: true, // 调试信息显示
				touchDistance: 0, // 滑动距离
				startVideoIndex: 0 // 记录滑动开始时的视频索引
			}
		},
		onLoad(options) {
			console.log('视频页面加载，参数:', options);
			// 从路由参数获取初始视频数据
			if (options.videoData) {
				try {
					this.initialVideo = JSON.parse(decodeURIComponent(options.videoData));
					console.log('解析到的初始视频:', this.initialVideo);
				} catch (e) {
					console.error('解析视频数据失败:', e);
				}
			}

			if (options.index) {
				this.currentIndex = parseInt(options.index) || 0;
			}

			this.initVideoList();
		},
		onUnload() {
			console.log('页面卸载，暂停视频');
			this.pauseCurrentVideo();
			this.resetState();
		},
		onHide() {
			console.log('页面隐藏，暂停视频');
			this.pauseCurrentVideo();
		},
		onShow() {
			console.log('页面显示，恢复播放');
			// 页面显示时恢复播放
			this.$nextTick(() => {
				setTimeout(() => {
					this.playCurrentVideo();
				}, 500);
			});
		},
		watch: {
			currentIndex(newIndex, oldIndex) {
				console.log(`视频切换: ${oldIndex} -> ${newIndex}`);
				// 切换视频时暂停上一个视频，播放当前视频
				if (oldIndex !== newIndex) {
					this.pauseVideo(oldIndex);
					this.$nextTick(() => {
						setTimeout(() => {
							this.playCurrentVideo();
						}, 100);
					});

					// 检查是否需要加载更多视频
					this.checkLoadMore(newIndex);
				}
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				console.log('返回上一页');
				uni.navigateBack();
			},

			// 获取视频的唯一key
			getVideoKey(video, index) {
				if (!video) return `video-${index}-${Date.now()}`;
				return video.id || video.contentId || `video-${index}-${Date.now()}`;
			},

			// 验证视频对象是否有效
			isValidVideo(video) {
				if (!video) return false;
				const url = this.getVideoUrl(video);
				console.log('验证视频:', video, 'URL:', url);
				return !!url;
			},

			// 获取视频URL
			getVideoUrl(video) {
				if (!video) return '';
				if (video.files && video.files[0] && video.files[0].fileUrl) {
					return video.files[0].fileUrl;
				}
				return video.videoUrl || video.url || '';
			},

			// 初始化视频列表
			initVideoList() {
				console.log('初始化视频列表');
				// 如果有初始视频数据
				if (this.initialVideo) {
					if (Array.isArray(this.initialVideo)) {
						this.videoList = this.initialVideo.filter(video => this.isValidVideo(video));
					} else if (this.isValidVideo(this.initialVideo)) {
						this.videoList = [this.initialVideo];
					} else {
						this.videoList = [];
					}
					console.log('初始视频列表:', this.videoList);
				} else {
					this.videoList = [];
				}

				this.pageNum = 1;
				this.hasMore = true;
				this.lastLoadIndex = 0;
				this.loading = false;

				// 如果没有初始视频或初始视频为空，加载更多视频
				if (this.videoList.length === 0) {
					console.log('没有初始视频，开始加载更多');
					this.loadMoreVideos();
				} else {
					// 有初始视频，直接播放第一个
					console.log('有初始视频，准备播放');
					this.$nextTick(() => {
						setTimeout(() => {
							this.playCurrentVideo();
						}, 500);
					});
				}
			},

			// 重置状态
			resetState() {
				console.log('重置状态');
				this.videoList = [];
				this.currentIndex = 0;
				this.pageNum = 1;
				this.hasMore = true;
				this.lastLoadIndex = 0;
				this.loading = false;

				// 清除滑动锁定时器
				if (this.swipeLockTimeout) {
					clearTimeout(this.swipeLockTimeout);
					this.swipeLockTimeout = null;
				}
				this.swipeLock = false;
				this.isSwiping = false;
				this.touchDistance = 0;

				// 清除视频上下文
				this.videoContexts = {};
			},

			// 检查是否需要加载更多视频
			checkLoadMore(currentIndex) {
				// 计算从上次加载后切换的视频数量
				const switchedCount = Math.abs(currentIndex - this.lastLoadIndex);

				// 如果切换次数达到阈值，且还有更多数据，则触发加载
				if (switchedCount >= this.loadThreshold && this.hasMore && !this.loading) {
					console.log(`切换次数达到阈值 ${this.loadThreshold}，触发加载更多`);
					this.loadMoreVideos();
					this.lastLoadIndex = currentIndex; // 更新上次加载的索引
				}

				// 如果接近列表末尾，也触发加载
				if (currentIndex >= this.videoList.length - 2 && this.hasMore && !this.loading) {
					console.log('接近列表末尾，触发加载更多');
					this.loadMoreVideos();
				}
			},

			// 加载更多视频
			loadMoreVideos() {
				if (this.loading || !this.hasMore) return;

				console.log('开始加载更多视频，页码:', this.pageNum);
				this.loading = true;

				let params = {
					userId: this.$store.state.userInfo.userId,
					contentType: 3,
					categoryId: 0,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
				};

				getVideos(params).then(res => {
					console.log('视频接口返回:', res);

					// 根据实际接口结构调整
					let responseData = res.data || res;

					if (responseData.code === 200) {
						const newVideos = responseData.rows || responseData.data || responseData.list || [];
						console.log('新视频数据:', newVideos);

						if (newVideos.length > 0) {
							// 过滤掉可能重复的视频（基于ID）
							const existingIds = new Set(this.videoList.map(v => this.getVideoKey(v)));
							const uniqueNewVideos = newVideos.filter(video => {
								if (!video) return false;
								const key = this.getVideoKey(video);
								return key && !existingIds.has(key);
							});

							console.log('去重后的新视频:', uniqueNewVideos);
							this.videoList.push(...uniqueNewVideos);
							this.pageNum++;

							// 检查是否还有更多数据
							this.hasMore = newVideos.length >= this.pageSize;
							console.log('是否还有更多数据:', this.hasMore);

							// 如果是第一次加载，播放第一个视频
							if (this.videoList.length === uniqueNewVideos.length) {
								this.$nextTick(() => {
									setTimeout(() => {
										this.playCurrentVideo();
									}, 200);
								});
							}
						} else {
							this.hasMore = false;
							console.log('没有更多视频数据');
							uni.showToast({
								title: '没有更多视频了',
								icon: 'none'
							});
						}
					} else {
						this.hasMore = false;
						console.error('获取视频列表失败:', responseData);
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					console.error('获取视频列表异常:', error);
					this.hasMore = false;
					this.loading = false;
					uni.showToast({
						title: '加载异常',
						icon: 'none'
					});
				}).finally(() => {
					this.loading = false;
					console.log('加载完成，当前视频总数:', this.videoList.length);
				});
			},

			// 获取视频上下文（App端专用）
			getVideoContext(videoId) {
				// #ifdef APP-PLUS
				if (!this.videoContexts[videoId]) {
					this.videoContexts[videoId] = uni.createVideoContext(videoId, this);
				}
				return this.videoContexts[videoId];
				// #endif

				// #ifndef APP-PLUS
				return null;
				// #endif
			},

			// 播放当前视频
			playCurrentVideo() {
				if (this.videoList.length === 0) {
					console.log('视频列表为空，无法播放');
					return;
				}

				const currentVideo = this.videoList[this.currentIndex];
				if (!this.isValidVideo(currentVideo)) {
					console.warn('当前视频无效，无法播放:', currentVideo);
					return;
				}

				const videoId = `video-${this.getVideoKey(currentVideo, this.currentIndex)}`;
				console.log('准备播放视频:', videoId, 'URL:', this.getVideoUrl(currentVideo));

				// #ifdef APP-PLUS
				try {
					const videoContext = this.getVideoContext(videoId);
					if (videoContext && typeof videoContext.play === 'function') {
						// 延迟播放以确保视频元素已准备好
						setTimeout(() => {
							console.log('App端播放视频');
							videoContext.play();
						}, 100);
					} else {
						console.warn('App端视频上下文获取失败');
					}
				} catch (error) {
					console.warn('App端播放视频异常:', error);
				}
				// #endif

				// #ifndef APP-PLUS
				this.$nextTick(() => {
					const videoElement = document.getElementById(videoId);
					if (videoElement && videoElement.play) {
						console.log('H5端播放视频');
						videoElement.play().catch(err => {
							console.warn('H5端视频播放失败:', err);
						});
					} else {
						console.warn('H5端视频元素未找到:', videoId);
					}
				});
				// #endif
			},

			// 暂停当前视频
			pauseCurrentVideo() {
				if (this.videoList.length === 0) return;

				const currentVideo = this.videoList[this.currentIndex];
				if (!currentVideo) return;

				const videoId = `video-${this.getVideoKey(currentVideo, this.currentIndex)}`;
				console.log('暂停视频:', videoId);

				// #ifdef APP-PLUS
				try {
					const videoContext = this.getVideoContext(videoId);
					if (videoContext && typeof videoContext.pause === 'function') {
						videoContext.pause();
					}
				} catch (error) {
					console.warn('App端暂停视频异常:', error);
				}
				// #endif

				// #ifndef APP-PLUS
				const videoElement = document.getElementById(videoId);
				if (videoElement && videoElement.pause) {
					videoElement.pause();
				}
				// #endif
			},

			// 暂停指定索引的视频
			pauseVideo(index) {
				if (index === this.currentIndex) {
					this.pauseCurrentVideo();
				}
			},

			// 视频加载完成
			onVideoLoaded(event) {
				console.log('视频加载完成');
			},

			// 视频加载错误
			onVideoError(event) {
				console.error('视频加载错误:', event);
				uni.showToast({
					title: '视频加载失败',
					icon: 'none'
				});
			},

			// 视频开始播放
			onVideoPlay(event) {
				console.log('视频开始播放');
			},

			// 视频暂停
			onVideoPause(event) {
				console.log('视频暂停');
			},

			// 触摸开始 - 修复版本
			handleTouchStart(event) {
				console.log('=== 触摸开始 ===');
				// 记录开始时的视频索引
				this.startVideoIndex = this.currentIndex;
				this.startY = event.touches[0].pageY;
				this.moveY = this.startY;
				this.touchStartTime = Date.now();
				this.isSwiping = true;
				this.touchDistance = 0;

				console.log('触摸开始，Y坐标:', this.startY, '当前索引:', this.currentIndex);
			},

			// 触摸移动 - 修复版本
			handleTouchMove(event) {
				if (!this.isSwiping) return;
				
				// 阻止默认滚动行为
				event.preventDefault();
				
				const currentY = event.touches[0].pageY;
				this.moveY = currentY;
				this.touchDistance = currentY - this.startY;
				
				console.log('触摸移动，距离:', this.touchDistance);
				
				// 实时更新transform实现跟随手指移动的效果
				if (Math.abs(this.touchDistance) > 10) {
					const progress = this.touchDistance / window.innerHeight;
					const targetIndex = this.startVideoIndex - Math.sign(progress) * Math.min(Math.abs(progress), 1);
					
					// 限制在有效范围内
					if (targetIndex >= 0 && targetIndex < this.videoList.length) {
						this.currentIndex = Math.round(targetIndex * 10) / 10; // 保留一位小数实现平滑过渡
					}
				}
			},

			// 触摸结束 - 修复版本
			handleTouchEnd(event) {
				if (!this.isSwiping) return;
				
				console.log('=== 触摸结束 ===');
				this.isSwiping = false;
				const endY = event.changedTouches[0].pageY;
				const distance = endY - this.startY;
				const duration = Date.now() - this.touchStartTime;
				
				console.log('触摸结束，滑动距离:', distance, '时间:', duration, '阈值:', this.swipeThreshold);
				
				// 判断是否为有效滑动
				if (Math.abs(distance) > this.swipeThreshold && duration < this.swipeTimeThreshold) {
					console.log('有效滑动，触发切换');
					this.handleSwipe(distance);
				} else {
					console.log('无效滑动，回弹到原位置');
					// 回弹到当前整数索引
					this.currentIndex = Math.round(this.currentIndex);
				}
			},

			// 处理滑动 - 修复版本
			handleSwipe(distance) {
				// 添加滑动锁防止快速滑动
				if (this.swipeLock) {
					console.log('滑动被锁定，忽略本次滑动');
					return;
				}

				// 设置滑动锁
				this.swipeLock = true;
				if (this.swipeLockTimeout) {
					clearTimeout(this.swipeLockTimeout);
				}
				this.swipeLockTimeout = setTimeout(() => {
					this.swipeLock = false;
					console.log('滑动锁定已解除');
				}, 400);

				console.log('处理滑动，距离:', distance, '当前索引:', this.currentIndex, '视频总数:', this.videoList.length);

				let newIndex = this.currentIndex;

				if (distance < -this.swipeThreshold) {
					// 向上滑动 - 切换到下一个视频
					newIndex = Math.min(this.currentIndex + 1, this.videoList.length - 1);
					console.log('上滑到下一个视频:', newIndex);
				} else if (distance > this.swipeThreshold) {
					// 向下滑动 - 切换到上一个视频
					newIndex = Math.max(this.currentIndex - 1, 0);
					console.log('下滑到上一个视频:', newIndex);
				} else {
					console.log('滑动距离不足，不切换');
					newIndex = Math.round(this.currentIndex); // 确保是整数
				}

				if (newIndex !== Math.round(this.currentIndex)) {
					console.log('执行切换:', Math.round(this.currentIndex), '->', newIndex);
					this.currentIndex = newIndex;
				} else {
					console.log('索引未变化，不执行切换');
					this.currentIndex = newIndex; // 确保是整数
				}
			},

			// 刷新视频列表
			refreshVideos() {
				console.log('刷新视频列表');
				this.resetState();
				this.initVideoList();
			}
		}
	};
</script>

<style lang="scss" scoped>
	.video-list-page {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		background-color: #000000;
		z-index: 9999;
		overflow: hidden;
		touch-action: none; /* 改为none防止浏览器默认滚动 */
	}

	.video-swiper {
		width: 100%;
		height: 100%;
		transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
		z-index: 1;
	}

	.video-item {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.video-player {
		width: 100%;
		height: 100%;
		object-fit: cover;
		z-index: 1;
		position: relative;
		background-color: #000000;
	}

	.video-info {
		position: absolute;
		bottom: 120px;
		left: 20px;
		right: 20px;
		color: white;
		z-index: 100;
		pointer-events: none;
	}

	.video-title {
		font-size: 18px;
		font-weight: bold;
		text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.7);
	}

	/* 蒙层 - 永远显示在视频上方 */
	.overlay-layer {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		z-index: 10000;
		pointer-events: none;

		>* {
			pointer-events: auto;
		}
	}

	.close-button {
		position: fixed;
		top: 60px;
		left: 20px;
		padding: 16px;
		background-color: rgba(0, 0, 0, 0.8);
		border-radius: 50%;
		z-index: 10010;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 64px;
		height: 64px;
		border: 2px solid rgba(255, 255, 255, 0.6);
		touch-action: manipulation;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);

		.back-icon {
			color: #FFFFFF;
			font-size: 28px;
			font-weight: bold;
		}

		&:active {
			transform: scale(0.95);
			background-color: rgba(0, 0, 0, 0.9);
		}
	}

	.video-indicator {
		position: fixed;
		top: 50%;
		right: 30px;
		transform: translateY(-50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		z-index: 10010;
		background-color: rgba(0, 0, 0, 0.3);
		padding: 10px 5px;
		border-radius: 20px;
	}

	.indicator-dot {
		width: 12px;
		height: 12px;
		border-radius: 50%;
		background-color: rgba(255, 255, 255, 0.4);
		margin: 8px 0;
		transition: all 0.3s ease;
	}

	.indicator-dot.active {
		background-color: #FFFFFF;
		transform: scale(1.4);
		box-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
	}

	.loading-indicator {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: white;
		font-size: 16px;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 10px 20px;
		border-radius: 20px;
		z-index: 100;
	}

	.empty-state {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: white;
		font-size: 18px;
		text-align: center;
		z-index: 100;

		.refresh-btn {
			margin-top: 20px;
			background-color: rgba(255, 255, 255, 0.2);
			color: white;
			border: none;
			padding: 10px 20px;
			border-radius: 20px;
		}
	}

	.video-invalid {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		background-color: #000;

		.invalid-text {
			color: #fff;
			font-size: 16px;
		}
	}

	/* 调试信息 - 放在最高层级 */
	.debug-info {
		position: fixed;
		top: 100px;
		left: 20px;
		background-color: rgba(0, 0, 0, 0.8);
		color: #00ff00;
		padding: 15px;
		border-radius: 8px;
		z-index: 10020;
		font-size: 14px;
		display: flex;
		flex-direction: column;
		gap: 8px;
		border: 1px solid #00ff00;
	}

	/* 专门的触摸层 - 修复版本 */
	.touch-layer {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		z-index: 10015;
		/* 在视频之上，但在UI控件之下 */
		/* background-color: rgba(255, 0, 0, 0.2); 调试时可以取消注释查看触摸区域 */
		pointer-events: auto;
		touch-action: none;
	}
</style>